<template>
  <div class="app-container">
    <br>
    <el-button type="primary" @click="addRoot()">添加根类</el-button>
    <br>
    <br>
    <el-table v-loading="listLoading" :data="treeData" style="width: 100%;margin-bottom: 20px;" row-key="id" border  :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :default-expand-all="true" :indent=60>
      <el-table-column prop="name" label="药品类型名称"  width="250" ></el-table-column>
      <el-table-column label="药品编码"  width="130" align="center">
        <template slot-scope="scope">
          <span :style="{'color': scope.row.abb.length == 1?'red':'black'}">{{ scope.row.abb[0] }}</span>
          <span v-if="scope.row.abb[1]" :style="{'color': scope.row.abb.length == 2?'red':'black'}">{{ scope.row.abb[1] }}</span>
          <span v-if="scope.row.abb[2]" :style="{'color': scope.row.abb.length == 3?'red':'black'}">{{ scope.row.abb[2] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="药品类型说明"  width="250" align="center"></el-table-column>
      <el-table-column label="操作" width="240" align="center">
        <template slot-scope="scope" >
          <div style="display: flex;flex-direction: row;justify-content: right;padding-left: 10px;padding-right: 15px;">
            <el-button type="primary" v-if="scope.row.level != 3"  @click="add(scope.row)" size="small">新增</el-button>
            <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
            <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="200" align="center">
        <template slot-scope="scope" >
          <el-button  @click="move(scope.row, 1)" size="small">上移</el-button>
          <el-button  @click="move(scope.row, 2)" size="small">下移</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false">
      <h2>类型信息</h2>
      <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
        <el-form-item label="上级id" v-if="false">
            <el-input v-model="form.id" :disabled="true" />
        </el-form-item>
        <el-form-item label="上级代码" v-if="form.parentId">
            <el-input v-model="form.parentAbb" :disabled="true" />
        </el-form-item>
        <el-form-item label="上级名称" v-if="form.parentId">
            <el-input v-model="form.parentName" :disabled="true" />
        </el-form-item>
        <el-form-item label="代码" prop="abb">
          <el-select v-model="form.abb" placeholder="请选择" style="width: 100%" v-if="form.level === 1">
            <el-option
              v-for="item in firstItemAbbEnm"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled">
            </el-option>
          </el-select>
          <el-select v-model="form.abb" placeholder="请选择" style="width: 100%" v-if="form.level === 2">
            <el-option
              v-for="item in secondItemAbbEnm"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled">
            </el-option>
          </el-select>
          <el-select v-model="form.abb" placeholder="请选择" style="width: 100%" v-if="form.level === 3">
            <el-option
              v-for="item in thirdItemAbbEnm"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="说明" >
            <el-input v-model="form.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
  </el-dialog>

  
  <el-dialog :title="dialogTitle" :visible.sync="rootFormVisible" :closeOnClickModal="false">
    <h2>类型信息</h2>
    <el-form ref="rootForm" :model="rootForm" label-width="80px" :rules="formRules">
      <el-form-item label="一级代码" prop="abb">
        <el-select v-model="rootForm.abb" placeholder="请选择" style="width: 100%" >
          <el-option
            v-for="item in firstItemAbbEnm"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="一级名称" prop="name">
          <el-input v-model="rootForm.name" />
      </el-form-item>
      <el-form-item label="二级代码" prop="abb2">
        <el-select v-model="rootForm.abb2" placeholder="请选择" style="width: 100%" >
          <el-option
            v-for="item in secondItemAbbEnm"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级名称" prop="name2">
          <el-input v-model="rootForm.name2" />
      </el-form-item>
      <el-form-item label="三级代码" prop="abb3">
        <el-select v-model="rootForm.abb3" placeholder="请选择" style="width: 100%" >
          <el-option
            v-for="item in thirdItemAbbEnm"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级名称" prop="name3">
          <el-input v-model="rootForm.name3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmRootForm">确 定</el-button>
        <div style="width:200px;display: inline-block;"> </div>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog :title="dialogTitle" :visible.sync="secondFormVisible" :closeOnClickModal="false">
    <h2>类型信息</h2>
    <el-form ref="secondForm" :model="secondForm" label-width="80px" :rules="formRules">
      <el-form-item label="二级代码" prop="abb2">
        <el-select v-model="secondForm.abb2" placeholder="请选择" style="width: 100%" >
          <el-option
            v-for="item in secondItemAbbEnm"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级名称" prop="name2">
          <el-input v-model="secondForm.name2" />
      </el-form-item>
      <el-form-item label="三级代码" prop="abb3">
        <el-select v-model="secondForm.abb3" placeholder="请选择" style="width: 100%" >
          <el-option
            v-for="item in thirdItemAbbEnm"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级名称" prop="name3">
          <el-input v-model="secondForm.name3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmSecondForm">确 定</el-button>
        <div style="width:200px;display: inline-block;"> </div>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  </div>
</template>


<script>
let id = 1000;
import { getTreeList, add, edit, del } from '@/api/drugType'

export default {
  name: "DrugType",
  filters: {
    
  },
  data() {
    const validateAbb = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入代码'))
      } else {
        callback()
      }
    }
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入名称'))
      } else {
        callback()
      }
    }
    return {
      listLoading: true,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      form: {},
      rootForm: {},
      secondForm: {},
      formVisible: false,
      rootFormVisible: false,
      secondFormVisible: false,
      treeData: [],
      dialogTitle: '类型详情',
      formRules: {
        abb: [{ required: true, trigger: 'blur', validator: validateAbb }],
        abb2: [{ required: true, trigger: 'blur', validator: validateAbb }],
        abb3: [{ required: true, trigger: 'blur', validator: validateAbb }],
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        name2: [{ required: true, trigger: 'blur', validator: validateName }],
        name3: [{ required: true, trigger: 'blur', validator: validateName }],
      },
      firstItemAbbEnm: [],
      secondItemAbbEnm: [],
      thirdItemAbbEnm: [],
    }
  },
  created() {
    document.getelement
    this.fetchData()
  },
  methods: {
    getChildren(drugType) {
      if(drugType.children && drugType.children.length > 0) {
        drugType.children.forEach(children=> {
          this.getChildren(children)
        })
      }
    },
    fetchData() {
      getTreeList().then(res=> {
        console.log(res)
        this.treeData = res.data
        // this.treeData.forEach(item=> {
        //   this.getChildren(item)
        // })
        this.listLoading = false
      }).catch(err=>{
        console.log(err)
      })
      this.firstItemAbbEnm = []
      this.secondItemAbbEnm = []
      this.thirdItemAbbEnm = []
      for (let i = 65; i <= 90; i++) {
        var val = String.fromCharCode(i);
        this.firstItemAbbEnm.push({id: val, name: val})
      }
      for (let i = 65; i <= 90; i++) {
        var val = String.fromCharCode(i);
        this.secondItemAbbEnm.push({id: val, name: val})
      }
      for (let i = 65; i <= 90; i++) {
        var val = String.fromCharCode(i);
        this.thirdItemAbbEnm.push({id: val, name: val})
      }
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改类型'
      this.form = JSON.parse(JSON.stringify(row))
      this.form.abb = this.form.abb[this.form.abb.length-1]
      this.secondItemAbbEnm.forEach(item=> {item.disabled = false})
      this.thirdItemAbbEnm.forEach(item=> {item.disabled = false})
      var brotherList = this.getBrotherList(row)
      if(this.form.level == 1) {
        this.firstItemAbbEnm.forEach(item=> {
        this.treeData.forEach(firstItem=> {
          if(item.name == firstItem.abb[firstItem.abb.length-1]) item.disabled = true
        })
      })
      } else if(this.form.level == 2) {
         this.secondItemAbbEnm.forEach(item=> {
          if(brotherList) {
            brotherList.forEach(item2 =>{
              if(item.name == item2.abb[item2.abb.length-1]) item.disabled = true
            })
          }
        })
      } else if (this.form.level == 3) {
        this.thirdItemAbbEnm.forEach(item=> {
          if(brotherList) {
            brotherList.forEach(item2 =>{
              if(item.name == item2.abb[item2.abb.length-1]) item.disabled = true
            })
          }
        })
      }
      this.formVisible = true
    },
    getBrotherList(drugTypeItem) {
      if(drugTypeItem.level == 1) return this.treeData
      var parentItem = this.getParent(drugTypeItem)
      return parentItem.children
    },
    getParent(drugTypeItem) {
      for (const first of this.treeData) {
        if(first.children) {
          for (const second of first.children) {
            if(drugTypeItem.id == second.id) {
              return first
            }
            if(second.children) {
              for (const third of second.children) {
                if(drugTypeItem.id == third.id) {
                  return second
                }
              }
            }
          }
        }
      }
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该类型?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          getTreeList().then(res=> {
            console.log(res)
            this.treeData = res.data
          }).catch(err=>{
            console.log(err)
          })
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    add(row) {
      console.log(row)
      this.reset()
      this.dialogTitle = '添加类型'
      this.secondItemAbbEnm.forEach(item=> {item.disabled = false})
      this.thirdItemAbbEnm.forEach(item=> {item.disabled = false})
      if(row.children) {
        if(row.level == 1) {
          this.secondItemAbbEnm.forEach(item=> {
            row.children.forEach(item2 =>{
              if(item.name == item2.abb[item2.abb.length-1]) item.disabled = true
            })
          })
        } else if (row.level == 2) {
          this.thirdItemAbbEnm.forEach(item=> {
            row.children.forEach(item2 =>{
              if(item.name == item2.abb[item2.abb.length-1]) item.disabled = true
            })
          })
        }
      }
      if(row.level == 1) {
        this.secondForm.parentId = row.root ? 0 : row.id
        this.secondForm.parentAbb = row.root ? undefined : row.abb[row.abb.length-1]
        this.secondForm.parentName = row.name
        this.secondForm.sort = row.root ? this.treeData.length+1 : (row.children ? row.children.length+1 : 1)
        this.secondForm.level = row.root ? 1 : row.level + 1
        this.secondFormVisible = true
      } else if(row.level == 2) {
        this.form.parentId = row.root ? 0 : row.id
        this.form.parentAbb = row.root ? undefined : row.abb[row.abb.length-1]
        this.form.parentName = row.name
        this.form.sort = row.root ? this.treeData.length+1 : (row.children ? row.children.length+1 : 1)
        this.form.level = row.root ? 1 : row.level + 1
        this.formVisible = true
      }
    },
    addRoot() {
      this.firstItemAbbEnm.forEach(item=> {
        this.treeData.forEach(firstItem=> {
          if(item.name == firstItem.abb[firstItem.abb.length-1]) item.disabled = true
        })
      })
      this.secondItemAbbEnm.forEach(item=> {item.disabled = false})
      this.thirdItemAbbEnm.forEach(item=> {item.disabled = false})
      this.rootFormVisible = true
    },
    confirm() {
      this.listLoading = true
      console.log(this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          var typeObj = this.form
          typeObj.parentId = this.form.parentId ? this.form.parentId : 0
          if(this.form.id) {
            edit(typeObj).then(res=>{
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.fetchData()
              this.formVisible = false
              this.listLoading = false
            })
          } else {
            add(typeObj).then(res=>{
              typeObj.id = res.data
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.fetchData()
              this.formVisible = false
              this.listLoading = false
            }).catch(err=>{
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      console.log(this.node)
      this.formVisible = false
    },
    reset() {
      this.form = {}
      this.rootForm = {}
    },
    cancel() {
      this.form = {}
      this.rootForm = {}
      this.formVisible = false
      this.rootFormVisible = false
    },
    inputAbb() {
      if(this.form.abb.replace(/[^a-z]/g, '')) this.form.abb = this.form.abb.toUpperCase()
      this.form.abb = this.form.abb.replace(/[^a-zA-Z]/g, '')
      if(this.form.abb.length > 1) {
        this.$message.error('只能输入1位英文字母')
        this.form.abb = this.form.abb[0]
      }
    },
    move(row, type) {
      this.listLoading = true
      var curList = this.getParentList(row, this.treeData)
      var rowIndex = curList.indexOf(row)
      if(type === 1) {
        // 上移
        if(rowIndex === 0) {
          this.listLoading = false
          return
        }
        curList[rowIndex].sort--
        curList[rowIndex-1].sort++
        curList[rowIndex-1].abb = curList[rowIndex-1].abb[curList[rowIndex-1].abb.length-1]
        edit(curList[rowIndex-1]).then(res=>{
          curList[rowIndex].abb = curList[rowIndex].abb[curList[rowIndex].abb.length-1]
          edit(curList[rowIndex]).then(res=>{
            this.formVisible = false
            this.listLoading = false
            this.$tab.refreshPage({path: '/store/type', name: "Type"})
          })
        })
      } else {
        // 下移
        if(rowIndex === curList.length-1) {
          this.listLoading = false
          return
        }
        curList[rowIndex+1].sort--
        curList[rowIndex+1].abb = curList[rowIndex+1].abb[curList[rowIndex+1].abb.length-1]
        edit(curList[rowIndex+1]).then(res=>{
          curList[rowIndex].sort++
          curList[rowIndex].abb = curList[rowIndex].abb[curList[rowIndex].abb.length-1]
          edit(curList[rowIndex]).then(res=>{
            this.formVisible = false
            this.listLoading = false
            this.$tab.refreshPage({path: '/store/type', name: "Type"})
          })
        })
      }
    },
    getParentList(row, treeData) {
      for (const item of treeData) {
        if(item.level === row.level && item.abb[item.abb.length-1] === row.abb[item.abb.length-1]) {
          return treeData
        }
        if(item.children) {
          var list = this.getParentList(row, item.children)
          if(list) return list
        }
      }
    },
    confirmRootForm() {
      console.log(this.rootForm)
      this.listLoading = true
      this.$refs.rootForm.validate(valid => {
        if (valid) {
          var firstType = {
            parentId: 0,
            abb: this.rootForm.abb,
            name: this.rootForm.name,
            level: 1,
            sort: this.treeData.length+1
          }
          add(firstType).then(res=>{
            console.log("first res", res)
            var secondType = {
              parentId: res.data,
              abb: this.rootForm.abb2,
              name: this.rootForm.name2,
              level: 2,
              sort: 1
            }
            add(secondType).then(res=>{
              var thirdType = {
                parentId: res.data,
                abb: this.rootForm.abb3,
                name: this.rootForm.name3,
                level: 3,
                sort: 1
              }
              add(thirdType).then(res=>{
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.fetchData()
                this.rootFormVisible = false
                this.listLoading = false
              })
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    confirmSecondForm() {
      console.log(this.secondForm)
      this.listLoading = true
      this.$refs.secondForm.validate(valid => {
        if (valid) {
          var secondType = {
            parentId: this.secondForm.parentId,
            abb: this.secondForm.abb2,
            name: this.secondForm.name2,
            level: 2,
            sort: this.secondForm.sort
          }
          add(secondType).then(res=>{
            var thirdType = {
              parentId: res.data,
              abb: this.secondForm.abb3,
              name: this.secondForm.name3,
              level: 3,
              sort: 1
            }
            add(thirdType).then(res=>{
              this.fetchData()
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.fetchData()
                this.listLoading = false
                this.secondFormVisible = false
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
  
}
</script>
